using System;
using System.Collections.Generic;
using System.Html;
using System.Runtime.CompilerServices;

namespace Awaiter
{
    public delegate int TimerClearDelegate(int timer); 

    [IgnoreNamespace]
    public class AwaitTimers
    {
        private readonly Dictionary<int, TimerClearDelegate> _timers = new Dictionary<int, TimerClearDelegate>();
        private static int _delayedSpinner;

        public int SetTimeout(Action fn, int ms)
        {
            int t = Window.SetTimeout(fn, ms);
            _timers[t] = (TimerClearDelegate)Script.Literal("clearTimeout");
            return t;
        }

        public int SetInterval(Action fn, int ms)
        {
            int t = Window.SetInterval(fn, ms);
            _timers[t] = (TimerClearDelegate)Script.Literal("clearInterval");
            return t;
        }

        public int ClearTimer(int timer)
        {
            TimerClearDelegate fn = _timers[timer];
            if (fn != null)
            {
                int ret = fn(timer);
                _timers.Remove(timer);
                return ret;
            }
            return 0;
        }

        public void ClearAll()
        {
            foreach (KeyValuePair<int, TimerClearDelegate> p in _timers)
            {
                ClearTimer(p.Key);
            }
        }

        public void StartDelayedSpinner()
        {
            return;
            if (_delayedSpinner > 0)
                return;
            Script.Literal("console.log('Starting delayed spinner')");
            _delayedSpinner = Window.SetTimeout(delegate { Await.Trigger("Spinner", true);}, 3000);
        }

        public void StopDelayedSpinner()
        {
            return;
            Script.Literal("console.log('Stopping delayed spinner')");
            Await.Trigger("Spinner", false);
            int sv = _delayedSpinner;
            _delayedSpinner = 0;
            Window.ClearTimeout(sv);
        }
    }
}
